package com.yeskery.nut.web.demo.biz;

import com.alibaba.fastjson2.JSON;
import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.annotation.transaction.Transactional;
import com.yeskery.nut.event.ApplicationEventPublisher;
import com.yeskery.nut.extend.i18n.MessageService;
import com.yeskery.nut.extend.memory.Storage;
//import com.yeskery.nut.extend.redis.JedisExecutor;
import com.yeskery.nut.script.function.extend.UuidFunction;
import com.yeskery.nut.script.function.security.Md5Function;
import com.yeskery.nut.util.DigestUtils;
import com.yeskery.nut.web.demo.common.Constants;
import com.yeskery.nut.web.demo.common.Log;
import com.yeskery.nut.web.demo.domain.User;
import com.yeskery.nut.web.demo.domain.Wallet;
import com.yeskery.nut.web.demo.dto.UserDto;
import com.yeskery.nut.web.demo.event.UserRegisterEvent;
import com.yeskery.nut.web.demo.exception.BusinessException;
import com.yeskery.nut.web.demo.service.UserService;
import com.yeskery.nut.web.demo.service.WalletService;

/**
 * 认证biz
 * @author Yeskery
 * 2023/7/28
 */
@Component
public class AuthBiz {

    private static final String REDIS_SUCCESS = "OK";

    @Autowired
    private UserService userService;

    @Autowired
    private WalletService walletService;

    @Autowired
    private MessageService messageService;

    //@Autowired
    //private JedisExecutor jedisExecutor;

    @Autowired
    private LogBiz logBiz;

    @Autowired
    private Storage storage;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Log("用户登录")
    public String login(String username, String password) {
        try {
            User user = userService.lambdaQuery()
                    .eq(User::getUsername, username)
                    .eq(User::getPassword, DigestUtils.md5DigestAsHex(password))
                    .one();
            if (user == null) {
                return null;
            }
            String token = new UuidFunction().apply(Boolean.FALSE.toString());
            UserDto userDto = new UserDto();
            userDto.setId(user.getId());
            userDto.setUsername(user.getUsername());
            userDto.setNickname(user.getNickname());
            /*jedisExecutor.execute(jedis -> jedis.setex(String.format(Constants.AUTH_TOKEN_REDIS_KEY, token),
                            Constants.AUTH_TOKEN_EXPIRED_SECONDS, JSON.toJSONString(userDto)));*/
            storage.set(String.format(Constants.AUTH_TOKEN_REDIS_KEY, token), JSON.toJSONString(userDto));
            logBiz.logByDefault("登陆成功");
            return token;
        } catch (Exception e) {
            throw new BusinessException(messageService.getMessage("r.fail"), e);
        }
    }

    /**
     * 注册
     * @param username
     * @param password
     * @param nickname
     */
    @Log("用户注册")
    @Transactional(rollbackFor = Exception.class)
    public void register(String username, String password, String nickname) {
        boolean exists = userService.lambdaQuery()
                .eq(User::getUsername, username)
                .exists();
        if (exists) {
            throw new BusinessException(messageService.getMessage("auth.register.username.fail"));
        }
        User user = new User();
        user.setUsername(username);
        try {
            user.setPassword(new Md5Function().apply(password));
        } catch (Exception e) {
            throw new BusinessException(messageService.getMessage("r.fail"), e);
        }
        user.setNickname(nickname);
        if (!userService.save(user)) {
            throw new BusinessException(messageService.getMessage("auth.register.fail"));
        }
        Wallet wallet = new Wallet();
        wallet.setUserId(user.getId());
        if (!walletService.save(wallet)) {
            throw new BusinessException(messageService.getMessage("auth.register.fail"));
        }

        // 发送用户注册事件
        eventPublisher.publishEvent(new UserRegisterEvent(user));
    }
}
